import { createEntityAdapter, createSlice, Draft, EntityState, PayloadAction } from "@reduxjs/toolkit";
import { AppState } from "@store/index";
import { persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";

// 在文件顶部添加类型定义
interface Channel {
    id: number
    [key: string]: any
}

// 创建访客频道列表实体适配器
const guestChannelEntityAdapter = createEntityAdapter<Channel>();

// 创建访客频道状态切片
const { reducer: guestChannelReducer, actions } = createSlice<
    EntityState<Channel, number>,
    {
        // 保存访客频道列表
        saveGuestChannels(
            state: Draft<EntityState<Channel, number>>,
            action: PayloadAction<Channel[]>
        ): void;
        // 根据 id 删除访客频道
        removeGuestChannel(
            state: Draft<EntityState<Channel, number>>,
            action: PayloadAction<number>
        ): void;
        // 添加访客频道
        addGuestChannel(
            state: Draft<EntityState<Channel, number>>,
            action: PayloadAction<Channel>
        ): void;
    },
    "guestChannels",
    never
>({
    name: "guestChannels",
    initialState: guestChannelEntityAdapter.getInitialState(),
    reducers: {
        // 保存访客频道列表
        saveGuestChannels: guestChannelEntityAdapter.setAll,
        // 根据 id 删除访客频道
        removeGuestChannel: guestChannelEntityAdapter.removeOne,
        // 添加访客频道
        addGuestChannel: guestChannelEntityAdapter.addOne,
    },
});

// 创建访客列表状态选择器
export const guestChannelSelectors =
    guestChannelEntityAdapter.getSelectors<AppState>(
        (state) => state.guestChannelReducer
    );

// 持久化
const persistGuestChannelReducer = persistReducer(
    { key: "guestChannelReducer", storage },
    guestChannelReducer
);

// 导出 Action Creator 函数
export const { saveGuestChannels, removeGuestChannel, addGuestChannel } = actions;
// 导出访客频道列表 Reducer 函数
export default persistGuestChannelReducer;